package com.wantup.controller.v6;

import com.wantup.model.InMessage;
import com.wantup.service.WebSocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName UserChatController
 * @Description TODO
 * @Author zhaoluowei
 * @Date 2019/6/24  21:13
 * @Version 1.0
 */

@Controller
public class UserChatController {

    @Autowired
    private WebSocketService webSocketService;

    //模拟数据
    public static Map<String, String> userMap = new HashMap<String, String>();

    static {
        userMap.put("zhangsan", "123");
        userMap.put("lisi", "456");
        userMap.put("wangwu", "789");
        userMap.put("tom", "000");
    }

    //在线用户
    public static Map<String, User> onlineUser = new ConcurrentHashMap<String, User>();

    static {
        onlineUser.put("123", new User("admin", "888"));


    }

    /**
     * 用户登录
     *
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String userLogin(@RequestParam("username") String username,
                            @RequestParam("pwd") String pwd,
                            HttpSession session) {

        String password = userMap.get(username);
        if (pwd.equals(password)) {
            User user = new User(username, pwd);
            onlineUser.put(session.getId(), user);
            return "redirect:/v6/chat.html";
        } else {
            return "redirect:/v6/error.html";

        }
    }

    @Scheduled(fixedRate = 2000)
    public void onlineUser(){
        webSocketService.sendOnlineUser(onlineUser);
    }

    /**
     * inMessage: --> 消息体
     * headerAccessor: --> 消息头访问器 通过这个获取sessionId
     * @param inMessage
     * @param headerAccessor
     */
    @MessageMapping(value = "/v6/chat")
    public void topicChat(InMessage inMessage, SimpMessageHeaderAccessor headerAccessor){
        String sessionId = headerAccessor.getSessionAttributes().get("sessionId").toString();
        User user = onlineUser.get(sessionId);

        inMessage.setFrom(user.getUsername());
        webSocketService.sendTopicChat(inMessage);


    }

}
